//
//  LoginViewController.m
//  安好
//
//  Created by 冯凯 on 14-10-30.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "LoginViewController.h"
#import "UserModel.h"
#import "ResisterView.h"
#import "AppDelegate.h"
#import "XGPush.h"
#import "UserModel.h"
#import "ForgotViewController.h"
#import "AppDelegate.h"
#import "ChatContent.h"
#import "SystemMessageCenter.h"
#import "UserId.h"
#import "DisclaimerViewController.h"
#import "CLDataBaseController.h"

@interface LoginViewController ()
{
    UIButton *rightButton;
    UIButton *skipAuthorButton;
}
@end
@implementation LoginViewController

- (void)viewWillAppear:(BOOL)animated
{

    self.navigationController.navigationBarHidden = NO;
    
    BOOL  wexin = [WXApi isWXAppInstalled];
    if (!wexin ){
        self.weixinButton.hidden = YES;
    }else{
        self.weixinButton.hidden = NO;
    }
    BOOL qq = [TencentOAuth iphoneQQInstalled];
    if (!qq) {
        self.QQButton.hidden = YES;
    }else{
        self.QQButton.hidden = NO;
    }
    if (!wexin && !qq) {
        self.weiboBuuton.frame = CGRectMake(kScreenWidth/2 - 32/2, 11, 32, 32);
    }else if (wexin && !qq){
        self.weiboBuuton.frame = CGRectMake(72, 11, 32, 32);
        self.weixinButton.frame = CGRectMake(247, 11, 32, 32);
    }else if (!wexin && qq){
        self.weiboBuuton.frame = CGRectMake(72, 11, 32, 32);
        self.QQButton.frame = CGRectMake(247, 11, 32, 32);
    }
   
}
- (void)viewDidAppear:(BOOL)animated
{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"ios8"];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    MyNSLog("%@", self.navigationController.viewControllers);
    //用药提醒监测通知
    
    self.navigationItem.title = @"登录";
    UIBarButtonItem *backBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(back:)];
    backBtnImg.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backBtnImg;
    rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(-20,0, 55, 23);
    [rightButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, -30)];
    rightButton.titleLabel.font = [UIFont systemFontOfSize:13];
    [rightButton setTitle:@"注册" forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(PushRegister:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    if (kScreenWidth == 320){
    self.backView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    self.shareQQView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - 54);
    self.anhaoLogo.frame = CGRectMake(kScreenWidth /2 - 76/2, 96, 76, 76);
    self.userNameTextField.frame = CGRectMake(86, 204, kScreenWidth - 116, 36);
    self.passWordTextField.frame = CGRectMake(86, 254, kScreenWidth - 116, 37);
    self.anhaoupLine.frame = CGRectMake(40, 244, kScreenWidth - 80, 1);
    self.anhaodownLine.frame = CGRectMake(40, 296, kScreenWidth - 80, 1);
    self.loginButton.frame = CGRectMake(40, 320, kScreenWidth - 80, 40);
    }else{
    self.backView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    self.shareQQView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - 54);
    self.anhaoLogo.frame = CGRectMake(kScreenWidth /2 - 92/2, 136, 92, 92);
    self.userNameTextField.frame = CGRectMake(86, 284, kScreenWidth - 116, 36);
    self.passWordTextField.frame = CGRectMake(86, 334, kScreenWidth - 116, 37);
    self.anhaoupLine.frame = CGRectMake(40, 324, kScreenWidth - 80, 1);
    self.anhaodownLine.frame = CGRectMake(40, 376, kScreenWidth - 80, 1);
    self.loginButton.frame = CGRectMake(40, 400, kScreenWidth - 80, 40);
    self.anhaouserImage.frame = CGRectMake(56, 291, 18, 18);
    self.anhaopasswordImage.frame = CGRectMake(56, 341, 18, 18);
    self.forgetButton.frame = CGRectMake(kScreenWidth - 105, 450, 76, 30);
    self.weixinButton.frame = CGRectMake(kScreenWidth/ 2 - 32/2, 11, 32, 32);
    self.QQButton.frame = CGRectMake(kScreenWidth - 32 - 71 , 11, 32, 32);
    }
    /**
     *  注册页面的空间
     */
    [self resgisterView];
    /**
     *  修改昵称
     */
    [self changeNickNameView];
    /**
     *  textField的代理
     */
    [self textFieldDelegate];
    /**
     *  加载中
     */
    [self loginActionView];
    /**
     *  收回登录键盘
     */
    [self tapLoginWithTextFieldResignFirstResponder];
    /**
     *  初始化QQ登录
     */
    [self loginQQ];
    /**
     *  新浪登录
     */
    [self loginSina];
    /**
     *  实名认证
     */
    [self RealNameAuthenticationView];

    [[NSNotificationCenter defaultCenter] addObserverForName:@"WeixinLogin" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification 	*note){
        self.weixinCode = [note.object objectForKey:@"code"];
        if ([self.weixinCode length] != 0) {
            [self getAccess_token];
        }
    }];
    [[NSNotificationCenter defaultCenter] addObserverForName:@"WeixinLogin1" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification 	*note){
        [self dismissViewControllerAnimated:YES completion:^{
            self.openid = nil;
            self.weixinCode = nil;
            self.access_token = nil;
            self.titleBackView.hidden=NO;
        }];
    }];
    self.loginQWView.frame = CGRectMake(0, kScreenHeight - 54 , kScreenWidth, 54);
}
/**
 *  收回登陆键盘
 */
- (void)tapLoginWithTextFieldResignFirstResponder
{
    UITapGestureRecognizer * tapLoginWithTextFieldResignFirstResponder = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapLoginWithTextFieldResignFirstResponder:)];
    [self.backView addGestureRecognizer:tapLoginWithTextFieldResignFirstResponder];
}
#pragma - mark textField的代理
/**
 * textField的代理
 */
- (void)textFieldDelegate
{
    self.userNameTextField.delegate = self;
    self.passWordTextField.delegate = self;
    self.resister.emailTextField.delegate = self;
    self.resister.userNameTextField.delegate = self;
    self.resister.passWordTextField.delegate = self;
    
}
/**
 *  iPhone4的动画
 *
 *  @param textField 用户名和密码
 *
 *  @return 无
 */
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (kScreenHeight == 480) {
        if (textField == self.userNameTextField || textField == self.passWordTextField){
            [UIView animateWithDuration:0.3 animations:^{
                self.backView.bottom = 350;
            } completion:^(BOOL finished) {
            }];
        }else{
            [UIView animateWithDuration:0.3 animations:^{
                self.resister.backView.frame = CGRectMake(0, -140, kScreenWidth , kScreenHeight);
            } completion:^(BOOL finished) {
            }];
        }
    }else{
        if (textField == self.resister.passWordTextField || textField == self.resister.emailTextField || textField == self.resister.userNameTextField){
            [UIView animateWithDuration:0.3 animations:^{
                self.resister.backView.frame = CGRectMake(0, -135, kScreenWidth, kScreenHeight);
            } completion:^(BOOL finished) {
            }];

        }
    }
    return YES;
}
/**
 *  iPhone4的动画
 *
 *  @param textField 用户名和密码
 *
 *  @return 无
 */
- (BOOL)textFieldShouldReturn:(UITextField *)textField;
{
    [textField resignFirstResponder];
    if (kScreenHeight == 480) {
        if (textField == self.userNameTextField || textField == self.passWordTextField){
            
            [UIView animateWithDuration:0.3 animations:^{
                self.backView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
            } completion:^(BOOL finished) {
            }];
        }else{
            [UIView animateWithDuration:0.3 animations:^{
                self.resister.backView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
            } completion:^(BOOL finished) {
            }];
        }
    }else{
        if (textField == self.resister.passWordTextField || textField == self.resister.emailTextField || textField == self.resister.userNameTextField) {
            
            [UIView animateWithDuration:0.3 animations:^{
                self.resister.backView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
            } completion:^(BOOL finished) {
            }];
        }
    }
    if (textField == self.resister.passWordTextField){
        if ([self.resister.userNameTextField.text length] == 0) {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"" message:@"请输入用户名" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }else if ([self.resister.emailTextField.text length] == 0){
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"" message:@"请输入邮箱" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }else{
            if (self.resister.unGreedImageView.hidden == NO){
                UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提醒" message:@"请先同意安好用户注册协议" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];
            }else{
                [self loginShowActionView];
                NSString * postURL = [NSString stringWithFormat:@"%@user/register/",kBaseURL];
                NSDictionary *LoginDic = @{
                                           @"username":self.resister.userNameTextField.text,
                                           @"email":self.resister.emailTextField.text,
                                           @"password":self.resister.passWordTextField.text,
                                           @"deviceid":@"",
                                           };
                self.qqOrWeiboUserDictionary = [NSDictionary dictionaryWithDictionary:LoginDic];
                NSString * userString = [LoginDic JSONString];
                NSString * encryptUserString = [ClassMethodsViewController encrypt:userString];
                AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
                NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"user":encryptUserString};
                [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
                    NSNumber * statusNum = [responseObject objectForKey:@"status"];
                    NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
                    NSString * statusString = [numberFormatter stringFromNumber:statusNum];
                    [self loginHiddenActionView];
                    if ([statusString isEqualToString:@"0"]) {
                        alertContent([responseObject objectForKey:@"msg"]);
                    }else{
                        NSDictionary * rooms = [RMMapper objectWithClass:[UserModel class] fromDictionary:[responseObject objectForKey:@"data"]];
                        NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
                        NSDictionary * dataDic = [responseObject objectForKey:@"data"];
                        NSString * uidKey = [NSString stringWithFormat:@"%@",[dataDic objectForKey:@"uid"]];
                        [XGPush setAccount:uidKey];
                        NSString * xgTokenData = [NSString stringWithFormat:@"%@",[AppDelegate app].tokenData];
                        if ([xgTokenData length] <= 8){
                        }else{
                            [XGPush registerDevice: [AppDelegate app].tokenData];
                        }
                        [[NSUserDefaults standardUserDefaults] setObject:uidKey forKey:@"SelfUidKey"];
                        NSString * userInfoKey = [NSString stringWithFormat:@"%@userInfoKey",uidKey];
                        NSMutableArray * userInfo = [[NSMutableArray alloc]init];
                        [userInfo addObject:rooms];
                        [defaults rm_setCustomObject:userInfo forKey:userInfoKey];
                        /**
                         *  跳转到实名认证
                         */
                        [self.resister.passWordTextField resignFirstResponder];

                        [self saveMyinfo:[responseObject objectForKey:@"data"]];
                        self.realName.isFromRegist=YES;
                        
                        [self showRealNameView];
                        
                    }
                    
                } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                    [self loginHiddenActionView];
                    
                }];
            }
            
        }
    }
    [textField resignFirstResponder];
    return YES;
}
- (void)tapLoginWithTextFieldResignFirstResponder:(UITapGestureRecognizer *)tapLoginWithTextFieldResignFirstResponder
{
    [UIView animateWithDuration:0.3 animations:^{
        self.backView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    } completion:^(BOOL finished) {
    }];
    [self.userNameTextField resignFirstResponder];
    [self.passWordTextField resignFirstResponder];
}
#pragma  -  mark 用户的登陆
/**
 *  用户登陆
 *
 *  @param sender 用户登陆
 */
- (IBAction)login:(UIButton *)sender
{

    sender.userInteractionEnabled = NO;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"loginTZ" object:nil];

    self.resister.resgistTitle.hidden = YES;
    self.resister.resgistSys.hidden = YES;
    [self.passWordTextField resignFirstResponder];
    [self.userNameTextField resignFirstResponder];
    
    [UIView animateWithDuration:0.3 animations:^{
        self.backView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    } completion:^(BOOL finished) {
    }];

    [self loginShowActionView];
    NSString * postURL = [NSString stringWithFormat:@"%@user/login/",kBaseURL];
    NSDictionary *LoginDic = @{
                               @"username":self.userNameTextField.text,
                               @"password":self.passWordTextField.text,
                               @"deviceid":@"",
                               };
    NSString * userString = [LoginDic JSONString];
    NSString * encryptUserString = [ClassMethodsViewController encrypt:userString];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"user":encryptUserString};
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        sender.userInteractionEnabled = YES;

        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        [self loginHiddenActionView];
        if ([statusString isEqualToString:@"0"]) {
            [self showCustomHudSingleLine:[responseObject objectForKey:@"msg"]];
        }else{
            NSDictionary * rooms = [RMMapper objectWithClass:[UserModel class] fromDictionary:[responseObject objectForKey:@"data"]];
            NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
            NSDictionary * dataDic = [responseObject objectForKey:@"data"];
            NSString * uidKey = [NSString stringWithFormat:@"%@",[dataDic objectForKey:@"uid"]];
            [XGPush setAccount:uidKey];
            NSString * xgTokenData = [NSString stringWithFormat:@"%@",[AppDelegate app].tokenData];
            if ([xgTokenData length] <= 8){
            }else{
                [XGPush registerDevice: [AppDelegate app].tokenData];
            }

            [[NSUserDefaults standardUserDefaults] setObject:uidKey forKey:@"SelfUidKey"];
            NSString * userInfoKey = [NSString stringWithFormat:@"%@userInfoKey",uidKey];
            NSMutableArray * userInfo = [[NSMutableArray alloc]init];
            [userInfo addObject:rooms];
            [defaults rm_setCustomObject:userInfo forKey:userInfoKey];
            
            [[CLDataBaseController instance] initSecretarySystemMessageForFirstResignOrLogin];//先插入

            [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreSystemNotification object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreNoticeNotification object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreNewsNotification object:nil];
                        
            [self saveMyinfo:dataDic];
            [[UserManager shareInstance]deleteUserImage];
            [self dismissViewControllerAnimated:YES completion:^{
                self.resister.resgistTitle.hidden = NO;
                self.resister.resgistSys.hidden = NO;
            }];
            //  判断我的好友的
            NSUserDefaults *firentDefaults = [NSUserDefaults standardUserDefaults];
            [firentDefaults setObject:@"firendUpdata" forKey:@"landing"];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        sender.userInteractionEnabled = YES;
        [self loginHiddenActionView];
        
    }];

}
- (void)realnameLogin
{
}
- (void)saveMyinfo:(NSDictionary *)dic
{
    
    NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];
    
    [[NSUserDefaults standardUserDefaults] setObject:[dic valueForKey:@"uid"] forKey:@"SelfUidKey"];
    
    if (![dic objectForKey:@"mobile_certification"]) {
        //是否手机认证
        [userDefaults setObject:@"0" forKey:@"authentication"];
    }else
    {
        //是否手机认证
        [userDefaults setObject:[NSString stringWithFormat:@"%@",[dic
            objectForKey:@"mobile_certification"]] forKey:@"authentication"];
    }
    if (![dic objectForKey:@"isarchives"]) {
        //是否完善档案
        [userDefaults setObject:@"0" forKey:@"archives"];
    }
    else
    {
        //是否完善档案
        [userDefaults setObject:[NSString stringWithFormat:@"%@",[dic objectForKey:@"isarchives"]] forKey:@"archives"];
    }
    if (![dic objectForKey:@"isinvite"]) {
        //是否邀请好友
        [userDefaults setObject:@"0" forKey:@"invite"];
    }
    else
    {
        //是否邀请好友
        [userDefaults setObject:[NSString stringWithFormat:@"%@",[dic objectForKey:@"isinvite"]] forKey:@"invite"];
    }
    
    
    if (![dic valueForKey:@"realname"]) {
        [userDefaults setValue:@"" forKey:[NSString stringWithFormat:@"%@realname",[dic valueForKey:@"uid"]]];
    }
    else
    {
        [userDefaults setValue:[dic valueForKey:@"realname"] forKey:[NSString stringWithFormat:@"%@realname",[dic valueForKey:@"uid"]]];
    }
    if (![dic valueForKey:@"mobile"]) {
        [userDefaults setValue:@"" forKey:[NSString stringWithFormat:@"%@mobile",[dic valueForKey:@"uid"]]];
    }else
    {
        [userDefaults setValue:[dic valueForKey:@"mobile"] forKey:[NSString stringWithFormat:@"%@mobile",[dic valueForKey:@"uid"]]];
    }
    if (![dic valueForKey:@"gender"]) {
        [userDefaults setValue:@"0" forKey:[NSString stringWithFormat:@"%@gender",[dic valueForKey:@"uid"]]];
    }
    else
    {
        [userDefaults setValue:[dic valueForKey:@"gender"] forKey:[NSString stringWithFormat:@"%@gender",[dic valueForKey:@"uid"]]];
    }
    
    if (![dic valueForKey:@"age"]) {
        [userDefaults setValue:@"-1" forKey:[NSString stringWithFormat:@"%@age",[dic valueForKey:@"uid"]]];
    }
    else
    {
        [userDefaults setValue:[dic valueForKey:@"age"] forKey:[NSString stringWithFormat:@"%@age",[dic valueForKey:@"uid"]]];
    }
    
    if (![dic valueForKey:@"mobile"]) {
        [userDefaults setValue:@"0" forKey:[NSString stringWithFormat:@"%@mobile",[dic valueForKey:@"uid"]]];
    }
    else if([[NSString stringWithFormat:@"%@",[dic valueForKey:@"mobile"]] length]>0)
    {
        [userDefaults setValue:[dic valueForKey:@"mobile"] forKey:[NSString stringWithFormat:@"%@mobile",[dic valueForKey:@"uid"]]];
    }else
    {
        [userDefaults setValue:@"0" forKey:[NSString stringWithFormat:@"%@mobile",[dic valueForKey:@"uid"]]];
    }

    [userDefaults synchronize];
    AppDelegate *dele=(AppDelegate*)[[UIApplication sharedApplication]delegate];
    [dele WBSocket];
}
#pragma  - mark 返回上级页面
/**
 *  用户返回上级页面
 *
 *  @param sender 用户返回上级页面
 */
- (void)back:(UIButton *)sender
{
    if ( self.isRes ==YES){
        self.navigationItem.title = @"登录";
        rightButton.hidden = NO;

        self.isRes = NO;
        [self.resister.emailTextField resignFirstResponder];
        [self.resister.userNameTextField resignFirstResponder];
        [self.resister.passWordTextField resignFirstResponder];
        [UIView animateWithDuration:0.3 animations:^{
        self.shareQQView.hidden = NO;
        self.titleBackView.hidden = NO;
        self.resister.frame = CGRectMake(0, kScreenHeight + 80, kScreenWidth, kScreenHeight);
        } completion:^(BOOL finished) {
        }];
    }else{
    [self dismissViewControllerAnimated:YES completion:^{

    }];
    }
}

#pragma - mark 跳转注册页面
/**
 *  跳转到到注册页面
 *
 *  @param sender 注册
 */
- (void)PushRegister:(UIButton *)button
{
    if (kScreenWidth != 320){
    /**
     *  注册
     */
    self.resister.anhaoLogo.frame = CGRectMake(kScreenWidth /2 - 76/2, 136, 76, 76);
    self.resister.anhaoEmail.frame = CGRectMake(56, 219+37, 18, 18);
    self.resister.emailTextField.frame = CGRectMake(86, 211+37, kScreenWidth - 116, 36);
    self.resister.anhaoupLine.frame = CGRectMake(40, 249+37, kScreenWidth - 80,1);
    self.resister.anhaoUser.frame = CGRectMake(56, 267+37, 18, 18);
    self.resister.userNameTextField.frame = CGRectMake(86, 260+37, kScreenWidth - 116, 36);
    self.resister.anhaomoddle.frame = CGRectMake(40, 301+37, kScreenWidth - 80, 1);
     self.resister.anhaoPass.frame = CGRectMake(56, 318+ 37, 18, 18);
    self.resister.passWordTextField.frame = CGRectMake(86, 312+ 37, kScreenWidth -116, 36);
    self.resister.anhaodown.frame = CGRectMake(40, 353+37, kScreenWidth - 80, 1);
    self.resister.greenButton.frame = CGRectMake(45, 358+37, 35, 35);
    self.resister.anhaoLabel.frame = CGRectMake(86, 364+37, 82, 21);
    self.resister.anhaoGreen.frame = CGRectMake(156, 360+37, 74, 30);
    self.resister.anhaoseleImage.frame = CGRectMake(55, 364+ 37, 18, 18);
    self.resister.resgistButton.frame = CGRectMake(40, 404+37, kScreenWidth - 80, 40);
    self.resister.greenImageView.frame = CGRectMake(56, 366+37, 18, 18);
    self.resister.unGreedImageView.frame = CGRectMake(56, 366+37, 18, 18);
    }else{
    self.resister.greenImageView.frame = CGRectMake(56, 366, 18, 18);
    self.resister.unGreedImageView.frame = CGRectMake(56, 366, 18, 18);
    }
    self.isRes = YES;
    self.navigationItem.title = @"注册";
    rightButton.hidden = YES;
    [self.userNameTextField resignFirstResponder];
    [self.passWordTextField resignFirstResponder];
    self.resister.backView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    self.backView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    
    self.shareQQView.hidden = YES;
    [UIView animateWithDuration:0.3 animations:^{
        self.resister.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
        
    } completion:^(BOOL finished) {
    }];

}
#pragma - mark 加载中
/**
 *  加载中
 */
- (void)loginActionView
{

    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"ios8"] length] != 0){
        if (IOS8_OR_LATER) {
            self.loginMBPro = [[MBProgressHUD alloc]initWithView:self.backView];
        }else{
            self.loginMBPro = [[MBProgressHUD alloc]initWithView:self.view];
        }
    }else{
        self.loginMBPro = [[MBProgressHUD alloc]initWithView:self.view];

    }
    [self.backView.superview addSubview:self.loginMBPro];
}
/**
 *  显示加载中
 */
- (void)loginShowActionView
{
    if (self.isRes){
        [self.loginMBPro setLabelText:@"注册中.."];
        
    }else{
        [self.loginMBPro setLabelText:@"登录中.."];
    }
    self.loginMBPro.mode = MBProgressHUDModeIndeterminate;
    [self.loginMBPro show:YES];
}
/**
 *  隐藏加载中
 */
- (void)loginHiddenActionView
{
    self.loginMBPro.mode = MBProgressHUDModeIndeterminate;
    [self.loginMBPro hide:YES];
}
#pragma - mark 注册页面
- (void)resgisterView
{
    /**
     *  注册页面
     */
    self.resister = [[[NSBundle mainBundle]loadNibNamed:@"ResisterView" owner:self options:nil] lastObject];
    self.resister.frame = CGRectMake(0, kScreenHeight, kScreenWidth, kScreenHeight);
    [self.backView addSubview:self.resister];
    /**
     *  跳转用户协议的Button
     *
     *  @param resgistBack: 无
     *
     *  @return 无
     */
    [self.resister.userDelegateButton addTarget:self action:@selector(userDelegateButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    /**
     *  返回页面，返回到登陆页面
     *
     *  @param resgistBack: 无
     *
     *  @return 无
     */
//    [self.resister.resgistBackButton addTarget:self action:@selector(resgistBack:) forControlEvents:UIControlEventTouchUpInside];
    /**
     *  注册页面的注册按钮
     *
     *  @param resgist: 无
     *
     *  @return 无
     */
    [self.resister.resgistButton addTarget:self action:@selector(resgist:) forControlEvents:UIControlEventTouchUpInside];
    /**
     *  是否同意用户协议
     *
     *  @param : 无
     *
     *  @return 无
     */
    [self.resister.greenButton addTarget:self action:@selector(greendUserDelegate
                                                               :) forControlEvents:UIControlEventTouchUpInside];
    UITapGestureRecognizer * tapRegistWithTextFieldResignFirstResponder = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapRegistWithTextFieldResignFirstResponder:)];
    [self.resister.backView addGestureRecognizer:tapRegistWithTextFieldResignFirstResponder];
    
}

#pragma -mark  跳转用户协议的Button相应事件 -
- (void)userDelegateButtonAction:(UIButton *)button{
    DisclaimerViewController *disclaimerVC = [[DisclaimerViewController alloc] init];
    UINavigationController *navigation = [[UINavigationController alloc] initWithRootViewController:disclaimerVC];
    disclaimerVC.isFromResister = YES;
     [self.navigationController presentViewController:navigation animated:YES completion:nil];
}


#pragma - mark 注册
/**
 *  注册
 *
 *  @param button 无
 */
- (void)resgist:(UIButton *)button
{
    [self.resister.emailTextField resignFirstResponder];
    [self.resister.userNameTextField resignFirstResponder];
    [self.resister.passWordTextField resignFirstResponder];

    [[NSNotificationCenter defaultCenter] postNotificationName:@"loginTZ" object:nil];
    
    if (self.resister.unGreedImageView.hidden == NO){
        [self showCustomHudSingleLine:@"请先同意安好用户注册协议"];

    }else{
        [self loginShowActionView];
        NSString * postURL = [NSString stringWithFormat:@"%@user/register/",kBaseURL];
        NSDictionary *LoginDic = @{
                                   @"username":self.resister.userNameTextField.text,
                                   @"email":self.resister.emailTextField.text,
                                   @"password":self.resister.passWordTextField.text,
                                   @"deviceid":@"",
                                   };
        self.qqOrWeiboUserDictionary = [NSDictionary dictionaryWithDictionary:LoginDic];
        NSString * userString = [LoginDic JSONString];
        NSString * encryptUserString = [ClassMethodsViewController encrypt:userString];
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"user":encryptUserString};
        [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSNumber * statusNum = [responseObject objectForKey:@"status"];
            NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
            NSString * statusString = [numberFormatter stringFromNumber:statusNum];
            [self loginHiddenActionView];
            if ([statusString isEqualToString:@"0"]) {
                [self showCustomHudSingleLine:[responseObject objectForKey:@"msg"]];
            }else{
                NSDictionary * rooms = [RMMapper objectWithClass:[UserModel class] fromDictionary:[responseObject objectForKey:@"data"]];
                NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
                NSDictionary * dataDic = [responseObject objectForKey:@"data"];
                NSString * uidKey = [NSString stringWithFormat:@"%@",[dataDic objectForKey:@"uid"]];
                [XGPush setAccount:uidKey];
                NSString * xgTokenData = [NSString stringWithFormat:@"%@",[AppDelegate app].tokenData];
                if ([xgTokenData length] <= 8){
                }else{
                    [XGPush registerDevice: [AppDelegate app].tokenData];
                }
                [[NSUserDefaults standardUserDefaults] setObject:uidKey forKey:@"SelfUidKey"];
                NSString * userInfoKey = [NSString stringWithFormat:@"%@userInfoKey",uidKey];
                NSMutableArray * userInfo = [[NSMutableArray alloc]init];
                [userInfo addObject:rooms];
                [defaults rm_setCustomObject:userInfo forKey:userInfoKey];
                self.isRes = NO;

                [[CLDataBaseController instance] initSecretarySystemMessageForFirstResignOrLogin];

                [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreSystemNotification object:nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreNoticeNotification object:nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreNewsNotification object:nil];
                
                [[SystemMessageCenter instance] loadDataForIsFirstResign:YES];
                
                /**
                 *  跳转到实名认证
                 */
                [self saveMyinfo:[responseObject objectForKey:@"data"]];
                self.realName.isFromRegist=YES;

                [self showRealNameView];

            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [self loginHiddenActionView];
            
        }];
    }
}
#pragma - mark 用户是否同意协议
- (void)greendUserDelegate:(UIButton *)button
{
    if (self.resister.greenImageView.hidden == YES){
        self.resister.greenImageView.hidden = NO;
        self.resister.unGreedImageView.hidden = YES;
    }else{
        self.resister.greenImageView.hidden = YES;
        self.resister.unGreedImageView.hidden = NO;
    }
}
#pragma - mark 手势收回键盘
- (void)tapRegistWithTextFieldResignFirstResponder:(UITapGestureRecognizer *)tapRegistWithTextFieldResignFirstResponder
{
    [UIView animateWithDuration:0.3 animations:^{
        self.resister.backView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    } completion:^(BOOL finished) {
    }];
    [self.resister.userNameTextField resignFirstResponder];
    [self.resister.passWordTextField resignFirstResponder];
    [self.resister.emailTextField resignFirstResponder];
    
}
#pragma  - mark QQ登陆
/**
 *  初始化QQ登陆
 */
- (void)loginQQ
{
    _permissions = [NSArray arrayWithObjects:
                    kOPEN_PERMISSION_GET_USER_INFO,
                    kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,
                    kOPEN_PERMISSION_GET_INFO,
                    nil];
    NSString *appid = @"101101365";
    _tencentOAuth = [[TencentOAuth alloc] initWithAppId:appid
                                            andDelegate:self];
}
/**
 *  QQ登陆
 *
 *  @param sender 无
 */
- (IBAction)QQLogin:(UIButton *)sender
{
    if ([TencentOAuth iphoneQQInstalled]){
        
        [_tencentOAuth authorize:_permissions inSafari:YES];
    }else{
        NSLog(@"dss");
        
    }
    

    
}
/**
 *  QQ登陆完成
 */
- (void)tencentDidLogin
{
    if (_tencentOAuth.accessToken
        && 0 != [_tencentOAuth.accessToken length])
    {
        if(![_tencentOAuth getUserInfo]){
            [self showInvalidTokenOrOpenIDMessage];
        }else{
            self.tencentOrSinaOAuthOpenID = [NSString stringWithFormat:@"%@",_tencentOAuth.openId];
        }
    }
    else
    {
        
    }
}
/**
 *  登陆失败
 *
 *  @param cancelled 无
 */
- (void)tencentDidNotLogin:(BOOL)cancelled
{
    if (cancelled){
        MyNSLog("用户取消登录");
    }
    else {
        MyNSLog("登录失败");
    }
}
/**
 *  登陆失败的提示
 */
- (void)showInvalidTokenOrOpenIDMessage
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"api调用失败" message:@"可能授权已过期，请重新获取" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
}
/**
 *  获得用户的资料
 *
 *  @param response 无
 */
- (void)getUserInfoResponse:(APIResponse*) response {
    if (response.retCode == URLREQUEST_SUCCEED)
    {
        NSMutableString *str=[NSMutableString stringWithFormat:@""];
        
        for (id key in response.jsonResponse) {
            [str appendString: [NSString stringWithFormat:@"%@:%@\n",key,[response.jsonResponse objectForKey:key]]];
        }
        NSString * nickname = [response.jsonResponse objectForKey:@"nickname"];
        NSString * avatar = [response.jsonResponse objectForKey:@"figureurl_2"];
        NSString * gender =[response.jsonResponse objectForKey:@"gender"];
        NSString * deviceID = [[UIDevice currentDevice] uniqueDeviceIdentifier];
        if ([nickname length] == 0) {
            nickname = @"";
        }
        if ([avatar length] == 0) {
            avatar = @"";
        }
        if ([gender length] == 0) {
            gender = @"";
        }
        if ([deviceID length] == 0) {
            deviceID = @"123";
        }
        self.qqOrWeiboUserDictionary  = @{
                                          @"nickname":nickname,
                                          @"openid":self.tencentOrSinaOAuthOpenID,
                                          @"avatar":avatar,
                                          @"gender":gender,
                                          @"deviceid":deviceID,
                                          };
        self.qqOrWeiboString = @"qq";
        [self followQQAndSina:@"qq" :nickname :avatar :gender :nil :nil];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"操作失败" message:[NSString stringWithFormat:@"%@", response.errorMsg]
                              
                                                       delegate:self cancelButtonTitle:@"我知道啦" otherButtonTitles: nil];
        [alert show];
    }
}
/**
 *  QQ登陆完成后，进入服务器，请求qq_login
 *
 *  @param nickname 用户名
 *  @param avatar   头像
 *  @param gender   性别
 */
- (void)QQlogin:(NSString *)nickname :(NSString *)avatar :(NSString *)gender
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"loginTZ" object:nil];


    NSString * deviceID = [[UIDevice currentDevice] uniqueDeviceIdentifier];
    NSString * postURL = [NSString stringWithFormat:@"%@user/qq_login",kBaseURL];
    if ([nickname length] == 0) {
        nickname = @"";
    }
    if ([avatar length] == 0) {
        avatar = @"";
    }
    if ([gender length] == 0) {
        gender = @"";
    }
    if ([deviceID length] == 0) {
        deviceID = @"123";
    }
    NSDictionary *LoginDic = @{
                               @"nickname":nickname,
                               @"openid":self.tencentOrSinaOAuthOpenID,
                               @"avatar":avatar,
                               @"gender":gender,
                               @"deviceid":deviceID,
                               };
    self.qqOrWeiboUserDictionary = [NSDictionary dictionaryWithDictionary:LoginDic];
    NSString * userString = [LoginDic JSONString];
    NSString * encryptUserString = [ClassMethodsViewController encrypt:userString];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"user":encryptUserString};
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject){
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        [self loginHiddenActionView];
        if ([statusString isEqualToString:@"0"]) {
            [self showCustomHudSingleLine:[responseObject objectForKey:@"msg"]];
        }else{
            NSDictionary * rooms = [RMMapper objectWithClass:[UserModel class] fromDictionary:[responseObject objectForKey:@"data"]];
            NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
            NSDictionary * dataDic = [responseObject objectForKey:@"data"];
            NSString * uidKey = [NSString stringWithFormat:@"%@",[dataDic objectForKey:@"uid"]];
            [XGPush setAccount:uidKey];
            NSString * xgTokenData = [NSString stringWithFormat:@"%@",[AppDelegate app].tokenData];
            if ([xgTokenData length] <= 8){
            }else{
                [XGPush registerDevice: [AppDelegate app].tokenData];
            }
            [[NSUserDefaults standardUserDefaults] setObject:uidKey forKey:@"SelfUidKey"];
            NSString * userInfoKey = [NSString stringWithFormat:@"%@userInfoKey",uidKey];
            NSMutableArray * userInfo = [[NSMutableArray alloc]init];
            [userInfo addObject:rooms];
            [defaults rm_setCustomObject:userInfo forKey:userInfoKey];
            
            [[CLDataBaseController instance] initSecretarySystemMessageForFirstResignOrLogin];

            [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreSystemNotification object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreNoticeNotification object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreNewsNotification object:nil];

            [self saveMyinfo:dataDic];
            [self dismissViewControllerAnimated:YES completion:^{
                self.titleBackView.hidden=NO;

            }];
            
            //  判断我的好友的
            NSUserDefaults *firentDefaults = [NSUserDefaults standardUserDefaults];
            [firentDefaults setObject:@"firendUpdata" forKey:@"landing"];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self loginHiddenActionView];
        
    }];
    
}
#pragma - mark 新浪SDK
/**
 *  初始化新浪微博
 */
- (void)loginSina
{
    
    [[NSNotificationCenter defaultCenter] addObserverForName:@"SinaLogin" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification 	*note){
        self.tencentOrSinaOAuthOpenID = [AppDelegate app].wbusid;
        NSString * nickname = [note.object objectForKey:@"name"];
        NSString * avatar = [note.object objectForKey:@"avatar_hd"];
        NSString * gender = [note.object objectForKey:@"gender"];
        NSString * description = [note.object objectForKey:@"description"];
        NSString * location = [note.object objectForKey:@"location"];
        NSString * deviceID = [[UIDevice currentDevice] uniqueDeviceIdentifier];
        if ([nickname length] == 0) {
            nickname = @"";
        }
        if ([avatar length] == 0) {
            avatar = @"";
        }
        if ([gender length] == 0) {
            gender = @"";
        }
        if ([deviceID length] == 0) {
            deviceID = @"123";
        }
        if ([description length] == 0) {
            description = @"";
        }
        if ([location length] == 0) {
            location = @"";
        }
        self.qqOrWeiboUserDictionary  = @{
                                   @"nickname":nickname,
                                   @"openid":self.tencentOrSinaOAuthOpenID,
                                   @"avatar":avatar,
                                   @"gender":gender,
                                   @"location":location,
                                   @"description":description,
                                   @"deviceid":deviceID,
                                   };
        self.qqOrWeiboString = @"weibo";
        [self followQQAndSina:@"weibo" :nickname :avatar :gender :description :location];
        
    }];
}
/**
 *  点击登陆
 *
 *  @param sender 无
 */
- (IBAction)loginSina:(UIButton *)sender
{
    WBAuthorizeRequest *request = [WBAuthorizeRequest request];
    request.redirectURI = kRedirectURI;
    request.scope = kAppSecret;
    request.userInfo = @{@"SSO_From": @"SendMessageToWeiboViewController",
                         @"Other_Info_1": [NSNumber numberWithInt:123],
                         @"Other_Info_2": @[@"obj1", @"obj2"],
                         @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
    [WeiboSDK sendRequest:request];

}
/**
 *  新浪登陆完成后，进入服务器，请求weibo_login
 *
 *  @param nickname    用户名
 *  @param avatar      头像
 *  @param gender      性别
 *  @param description 签名
 *  @param location    地区
 */
- (void)sinalogin:(NSString *)nickname :(NSString *)avatar :(NSString *)gender :(NSString *)description :(NSString *)location
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"loginTZ" object:nil];
    [[UserManager shareInstance]deleteUserImage];

    NSString * deviceID = [[UIDevice currentDevice] uniqueDeviceIdentifier];
    NSString * postURL = [NSString stringWithFormat:@"%@user/weibo_login/",kBaseURL];
    if ([nickname length] == 0) {
        nickname = @"";
    }
    if ([avatar length] == 0) {
        avatar = @"";
    }
    if ([gender length] == 0) {
        gender = @"";
    }
    if ([deviceID length] == 0) {
        deviceID = @"123";
    }
    if ([description length] == 0) {
        description = @"";
    }
    if ([location length] == 0) {
        location = @"";
    }
    NSDictionary *LoginDic = @{
                               @"nickname":nickname,
                               @"openid":self.tencentOrSinaOAuthOpenID,
                               @"avatar":avatar,
                               @"gender":gender,
                               @"location":location,
                               @"description":description,
                               @"deviceid":deviceID,
                               };
    self.qqOrWeiboUserDictionary = [NSDictionary dictionaryWithDictionary:LoginDic];
    NSString * userString = [LoginDic JSONString];
    NSString * encryptUserString = [ClassMethodsViewController encrypt:userString];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"user":encryptUserString};
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject){
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        [self loginHiddenActionView];
        if ([statusString isEqualToString:@"0"]) {
            [self showCustomHudSingleLine:[responseObject objectForKey:@"msg"]];
        }else{
            if (self.isChangeNameWeibo) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"isChangeName" object:nil];

            }
            NSDictionary * rooms = [RMMapper objectWithClass:[UserModel class] fromDictionary:[responseObject objectForKey:@"data"]];
            NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
            NSDictionary * dataDic = [responseObject objectForKey:@"data"];
            NSString * uidKey = [NSString stringWithFormat:@"%@",[dataDic objectForKey:@"uid"]];
            [XGPush setAccount:uidKey];
            NSString * xgTokenData = [NSString stringWithFormat:@"%@",[AppDelegate app].tokenData];
            if ([xgTokenData length] <= 8){
            }else{
                [XGPush registerDevice: [AppDelegate app].tokenData];
            }
            [[NSUserDefaults standardUserDefaults] setObject:uidKey forKey:@"SelfUidKey"];
            NSString * userInfoKey = [NSString stringWithFormat:@"%@userInfoKey",uidKey];
            NSMutableArray * userInfo = [[NSMutableArray alloc]init];
            [userInfo addObject:rooms];
            [defaults rm_setCustomObject:userInfo forKey:userInfoKey];
            
            [[CLDataBaseController instance] initSecretarySystemMessageForFirstResignOrLogin];

            [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreSystemNotification object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreNoticeNotification object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreNewsNotification object:nil];

            [self saveMyinfo:dataDic];
            [self dismissViewControllerAnimated:YES completion:^{
                self.titleBackView.hidden=NO;

            }];
            //  判断我的好友的
            NSUserDefaults *firentDefaults = [NSUserDefaults standardUserDefaults];
            [firentDefaults setObject:@"firendUpdata" forKey:@"landing"];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self loginHiddenActionView];
        
    }];
}
#pragma - mark 微信登录
/**
 *  微信登录
 *
 *  @param sender 微信登录
 */
- (IBAction)weixinLogin:(UIButton *)sender
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"WeixinBack" object:nil];

    [self sendAuthRequest];
    
}
int coun = 0;
-(void)sendAuthRequest
{

    SendAuthReq* req =[[SendAuthReq alloc] init];
    req.scope = @"snsapi_userinfo";
    [WXApi sendReq:req];
   
}
-(void)getAccess_token
{
    [[NSNotificationCenter defaultCenter] removeObserver:nil name:@"WeixinLogin" object:self];

    [self loginShowActionView];
    
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",kWXAppKey,kWXAppSecret,self.weixinCode];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (data) {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                self.access_token = [dic objectForKey:@"access_token"];
                self.openid = [dic objectForKey:@"openid"];
                if ([self.access_token length] != 0 && [self.openid length] != 0 ) {
                    [self getUserInfo1];
                }
            }
        });
    });
}
-(void)getUserInfo1
{
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",self.access_token,self.openid];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (data) {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                MyNSLog("dic == %@", dic);
                NSString * nickname = [dic objectForKey:@"nickname"];
                NSString * avatar = [dic objectForKey:@"headimgurl"];
                NSString * gender = [NSString stringWithFormat:@"%@",[dic objectForKey:@"sex"]];
                NSString * deviceID = [[UIDevice currentDevice] uniqueDeviceIdentifier];
                if ([nickname length] == 0) {
                    nickname = @"";
                }
                if ([avatar length] == 0) {
                    avatar = @"";
                }
                if ([gender length] == 0) {
                    gender = @"";
                }
                if ([deviceID length] == 0) {
                    deviceID = @"123";
                }
                self.qqOrWeiboUserDictionary  = @{
                                                  @"nickname":nickname,
                                                  @"openid":self.openid,
                                                  @"avatar":avatar,
                                                  @"gender":gender,
                                                  @"deviceid":deviceID,
                                                  };
                self.qqOrWeiboString = @"weixin";
                self.tencentOrSinaOAuthOpenID = self.openid;
                [self followQQAndSina:@"weixin" :nickname :avatar :gender :self.openid :deviceID];
            }
        });
        
    });
}

- (void)weixinlogin:(NSString *)nickname :(NSString *)avatar :(NSString *)gender :(NSString *)description :(NSString *)location
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"loginTZ" object:nil];
    [[UserManager shareInstance]deleteUserImage];

    NSString * deviceID = [[UIDevice currentDevice] uniqueDeviceIdentifier];
    NSString * postURL = [NSString stringWithFormat:@"%@user/weixin_login/",kBaseURL];
    if ([nickname length] == 0) {
        nickname = @"";
    }
    if ([avatar length] == 0) {
        avatar = @"";
    }
    if ([gender length] == 0) {
        gender = @"";
    }
    if ([deviceID length] == 0) {
        deviceID = @"123";
    }
    if ([description length] == 0) {
        description = @"";
    }
    if ([location length] == 0) {
        location = @"";
    }
    NSDictionary *LoginDic = @{
                               @"nickname":nickname,
                               @"openid":self.tencentOrSinaOAuthOpenID,
                               @"avatar":avatar,
                               @"gender":gender,
                               @"location":location,
                               @"description":description,
                               @"deviceid":deviceID,
                               };
    self.qqOrWeiboUserDictionary = [NSDictionary dictionaryWithDictionary:LoginDic];
    NSString * userString = [LoginDic JSONString];
    NSString * encryptUserString = [ClassMethodsViewController encrypt:userString];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"user":encryptUserString};
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject){
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        [self loginHiddenActionView];
        if ([statusString isEqualToString:@"0"]) {
            [self showCustomHudSingleLine:[responseObject objectForKey:@"msg"]];
        }else{
            NSDictionary * rooms = [RMMapper objectWithClass:[UserModel class] fromDictionary:[responseObject objectForKey:@"data"]];
            NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
            NSDictionary * dataDic = [responseObject objectForKey:@"data"];
            NSString * uidKey = [NSString stringWithFormat:@"%@",[dataDic objectForKey:@"uid"]];
            [XGPush setAccount:uidKey];
            NSString * xgTokenData = [NSString stringWithFormat:@"%@",[AppDelegate app].tokenData];
            if ([xgTokenData length] <= 8){
            }else{
                [XGPush registerDevice: [AppDelegate app].tokenData];
            }
            [[NSUserDefaults standardUserDefaults] setObject:uidKey forKey:@"SelfUidKey"];
            NSString * userInfoKey = [NSString stringWithFormat:@"%@userInfoKey",uidKey];
            NSMutableArray * userInfo = [[NSMutableArray alloc]init];
            [userInfo addObject:rooms];
            [defaults rm_setCustomObject:userInfo forKey:userInfoKey];
            
            [[CLDataBaseController instance] initSecretarySystemMessageForFirstResignOrLogin];

            [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreSystemNotification object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreNoticeNotification object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreNewsNotification object:nil];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"WeixinLogin1" object:nil];
            [self saveMyinfo:dataDic];
            
            
            //  判断我的好友的
            NSUserDefaults *firentDefaults = [NSUserDefaults standardUserDefaults];
            [firentDefaults setObject:@"firendUpdata" forKey:@"landing"];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self loginHiddenActionView];
        
    }];
}

#pragma mark 判断是否登陆过
/**
 *  判断是否登录过
 *
 *  @param action      登录的类型
 *  @param nickname    用户名
 *  @param avatar      头像
 *  @param gender      性别
 *  @param description 签名
 */
- (void)followQQAndSina:(NSString *)action :(NSString *)nickname :(NSString *)avatar :(NSString *)gender :(NSString *)description :(NSString *)location
{
    [self loginShowActionView];
    
    NSString * postURL = [NSString stringWithFormat:@"%@user/follow/",kBaseURL];
    if ([nickname length] == 0) {
        nickname = @"";
    }
    if ([location length] == 0) {
        location = @"";
    }
    if ([description length] == 0) {
        description = @"";
    }
    NSDictionary *LoginDic = @{
                               @"action":action,
                               @"openid":self.tencentOrSinaOAuthOpenID,
                               @"nickname":nickname,
                               };
    NSString * userString = [LoginDic JSONString];
    NSString * encryptUserString = [ClassMethodsViewController encrypt:userString];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"user":encryptUserString};
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString * msgString = [responseObject objectForKey:@"msg"];
        if ([msgString isEqualToString:@"success"]) {
            if ([action isEqualToString:@"qq"]){
                [self QQlogin:nickname :avatar :gender];
            }else if ([action isEqualToString:@"weibo"]){
                [self sinalogin:nickname :avatar :gender :description :location];
            }else{
                [self weixinlogin:nickname :avatar :gender :description :location];
            }
        }else{
            [self loginHiddenActionView];
            
            self.navigationItem.title = @"修改昵称";
            rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
            rightButton.frame = CGRectMake(-20,0, 55, 23);
            [rightButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, -30)];
            rightButton.titleLabel.font = [UIFont systemFontOfSize:13];
            [rightButton setTitle:@"" forState:UIControlStateNormal];
            self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
            
            UIBarButtonItem *OkBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_完成.png"] style:UIBarButtonItemStylePlain target:self action:@selector(changeNameFinish:)];
            OkBtnImg.tintColor = [UIColor whiteColor];
            self.navigationItem.rightBarButtonItem = OkBtnImg;

            
            [UIView animateWithDuration:0.3 animations:^{
                self.changeNickName.changeNickNameTextField.text = [self.qqOrWeiboUserDictionary objectForKey:@"nickname"];
                
                
                self.changeNickName.frame = CGRectMake(0, 0, kScreenHeight, kScreenHeight);
            } completion:^(BOOL finished) {
                self.titleBackView.hidden=YES;
            }];
            
            //  判断我的好友的
            NSUserDefaults *firentDefaults = [NSUserDefaults standardUserDefaults];
            [firentDefaults setObject:@"firendUpdata" forKey:@"landing"];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self loginHiddenActionView];
    }];
    
}

#pragma - mark 修改昵称
- (void)changeNickNameView
{
    
    self.changeNickName = [[[NSBundle mainBundle]loadNibNamed:@"ChangeNickName" owner:self options:nil] lastObject];
    
    
    self.changeNickName.frame = CGRectMake(kScreenWidth, 0, kScreenWidth, kScreenHeight);
//    [self.changeNickName.changeNameFinish addTarget:self action:@selector(changeNameFinish:) forControlEvents:UIControlEventTouchUpInside];
    [self.backView addSubview:self.changeNickName];
}
/**
 *  确定修改昵称
 *
 *  @param button 无
 */
- (void)changeNameFinish:(UIButton *)button
{
    [self loginShowActionView];
   
    NSString * postURL = [NSString stringWithFormat:@"%@user/checkusername/",kBaseURL];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"username":self.changeNickName.changeNickNameTextField.text};
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString * msgString = [responseObject objectForKey:@"msg"];
        if ([msgString isEqualToString:@"success"]) {
            NSString * avatar = [self.qqOrWeiboUserDictionary objectForKey:@"avatar"];
            NSString * gender = [self.qqOrWeiboUserDictionary objectForKey:@"gender"];
            NSString * description = [self.qqOrWeiboUserDictionary objectForKey:@"description"];
            NSString * location = [self.qqOrWeiboUserDictionary objectForKey:@"location"];

            if ([self.qqOrWeiboString isEqualToString:@"qq"]) {
                [self QQlogin:self.changeNickName.changeNickNameTextField.text :avatar :gender];
            }else if ([self.qqOrWeiboString isEqualToString:@"weibo"]){
                self.isChangeNameWeibo = YES;
                [self sinalogin:self.changeNickName.changeNickNameTextField.text :avatar :gender :description :location];
            }else{
                [self weixinlogin:self.changeNickName.changeNickNameTextField.text :avatar :gender :description :location];
            }
        }else{
            [self loginHiddenActionView];
            [self showCustomHudSingleLine:[responseObject objectForKey:@"msg"]];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self loginHiddenActionView];
    }];
}
#pragma mark 实名认证
/**
 *  实名认证
 */
- (void)RealNameAuthenticationView
{
    if (kScreenWidth==414) {
        self.realName=[[[NSBundle mainBundle] loadNibNamed:@"RealNameAuthentication" owner:self options:nil] lastObject];

    }else{
        self.realName=[[[NSBundle mainBundle] loadNibNamed:@"RealNameAuthentication" owner:self options:nil] firstObject];

    }
    self.realName.frame=CGRectMake(0, kScreenHeight+100, kScreenWidth, kScreenHeight-iOS7TopMargin);
    self.realName.realDelegate=self;
    self.realName.userName.delegate=self.realName;
    self.realName.telPhone.delegate=self.realName;
    self.realName.verificationCode.delegate=self.realName;
    self.realName.finishSender.hidden=YES;
//    self.realName
//    [self.realName.remindLabel sizeToFit];
    if (self.realName.remindLabel.text) {
        [self autosizeFontAndSize:self.realName.remindLabel withText:self.realName.remindLabel.text];

    }
    [self.backView addSubview:self.realName];
}
/**
 *  实名认证界面弹出动画
 */
- (void)showRealNameView
{
    if (!self.realName.isFromRegist) {
        self.realName.skipSender.hidden=YES;
        self.realName.skipRightButton.hidden=YES;
        self.realName.finishSender.hidden=YES;
        self.realName.finishButton.hidden=NO;
        skipAuthorButton=[UIButton buttonWithType:UIButtonTypeCustom];
        skipAuthorButton.titleLabel.font=[UIFont systemFontOfSize:15];
        skipAuthorButton.frame=CGRectMake(0, 0, 60, 30);
        [skipAuthorButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 20, 0, 0)];
        [skipAuthorButton setTitle:@"跳过" forState:UIControlStateNormal];
        [skipAuthorButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [skipAuthorButton addTarget:self action:@selector(dosekip:) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:skipAuthorButton];
    }
    else
    {
        self.realName.finishButton.hidden=YES;
        self.realName.skipRightButton.hidden=NO;
        self.realName.finishSender.hidden=NO;
    }
    self.navigationItem.title=@"实名认证";
    NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];
    UserModel *userModel = [[UserManager shareInstance]getUserInfo];

    if (![[userdefault valueForKey:[NSString stringWithFormat:@"%@realname",userModel.uid]]  length] == 0) {
        self.realName.userName.text=[userdefault valueForKey:[NSString stringWithFormat:@"%@realname",userModel.uid]];
        self.realName.userName.userInteractionEnabled=NO;
    }else{
        self.realName.userName.userInteractionEnabled=YES;
    }
    self.titleBackView.hidden=YES;
    [self.realName KeyboardWillHiden];
    [UIView animateWithDuration:0.3 animations:^{
        self.shareQQView.hidden = YES;
        self.realName.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    } completion:^(BOOL finished) {
    }];
}
-(void)dosekip:(UIButton *)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark 实名认证代理
- (void)dismissLogInController
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)finishRealNameAuthor
{
    if (self.realName.userName.text.length<=0) {
        [self alertShowString:@"请填写姓名"];
        return;
    }
    if (self.realName.telPhone.text.length<=0) {
        [self alertShowString:@"请填写手机号"];
        return;
    }
    if (self.realName.verificationCode.text.length<=0) {
        [self alertShowString:@"请填写验证码"];
        return;
    }
    
    NSString * postURL = [NSString stringWithFormat:@"%@/user/certification/",kBaseURL];
    NSString * deviceID = [[UIDevice currentDevice] uniqueDeviceIdentifier];
    
    if ([deviceID length] == 0) {
        deviceID = @"123";
    }

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *dic =     @{
                              @"realname":self.realName.userName.text,
                              @"mobile":self.realName.telPhone.text,
                              @"vercode":self.realName.verificationCode.text,
                              @"deviceid":deviceID,
                            };
    NSString *codeStr=[dic JSONString];
    NSDictionary *parameters=@{@"platform": kPlatform,
                               @"version":kVersion,
                               @"user":[ClassMethodsViewController encrypt:codeStr]
                               };
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *status=[NSString stringWithFormat:@"%@",[responseObject objectForKey:@"status"]];
        if ([status isEqualToString:@"1"]){
            
            UserModel * userModel = [[UserManager shareInstance]getUserInfo];
            NSString *myuid=userModel.uid;
            NSString *name=userModel.username;
            NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];
            [userDefaults setValue:self.realName.telPhone.text forKey:[NSString stringWithFormat:@"%@mobile",myuid]];
                            //是否手机认证
            [userDefaults setObject:@"1" forKey:@"authentication"];
            [userDefaults setObject:self.realName.userName.text forKey:[NSString stringWithFormat:@"%@realname",myuid]];
            NSString *realname=[userDefaults valueForKey:[NSString stringWithFormat:@"%@realname",myuid]];
            [userDefaults synchronize];

            AppDelegate *dele=(AppDelegate*)[[UIApplication sharedApplication]delegate];
            NSString *receiveDateline = [ChatContent readTheLastDate];

            NSDictionary *loginDict = [[NSDictionary alloc] initWithObjectsAndKeys:@"login", @"action",myuid, @"uid",name ,@"username",realname,@"realname", receiveDateline?:@"0",@"dateline",kPlatform, @"platform", nil];
            [dele.webSocket send:[loginDict JSONString]];
//            [self saveMyinfo:[responseObject valueForKey:@"data"]];

            [self dismissViewControllerAnimated:YES completion:nil];
        }else
        {
            [self showCustomHudSingleLine:[responseObject objectForKey:@"msg"]];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    }];

}
- (void)alertShowString:(NSString *)string
{
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:string delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}
/**
 *  忘记密码
 *
 *  @param sender 无
 */
- (IBAction)forgotPassword:(UIButton *)sender
{
    
    ForgotViewController * forgotViewController = [[ForgotViewController alloc]initWithNibName:@"ForgotViewController" bundle:nil];
    [self.navigationController pushViewController:forgotViewController animated:YES];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)autosizeFontAndSize:(UILabel *)label withText:(NSString *)text
{
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:label.text];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    NSLog(@"%f",kScreenWidth);
    if (kScreenWidth==320) {
        [paragraphStyle setLineSpacing:1];//调整行间距
    }else if(kScreenWidth==375)
    {
        [paragraphStyle setLineSpacing:1];//调整行间距
    }
    else if(kScreenWidth==414)
    {
        [paragraphStyle setLineSpacing:6];//调整行间距
    }
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [text length])];
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
    label.attributedText = attributedString;
    [label sizeToFit];
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
@end
